;(function($,w){
//	function _camel(obj){
//		var r = {};
//		for (var p in obj){
//			var c = _toCamelCase(p);
//			r[c] = obj[p];
//		}
//		return r;
//	};
	function _toCamelCase(n){
		return n.replace(/_([a-z])/g, function(t){return t.substring(1).toUpperCase();});
	}
	var TripAPI = {
			cpath:"",
			init:function(cpath){
				this.cpath = cpath;
			},
			camel:function(s){
				if (this.isArray(s)){
					var r = [];
					for (var i in s){
						var c = this.camel(s[i]);
						r.push(c);
					}
					return r;
				} else if (typeof s == 'object'){
					var r = {};
					for (var p in s){
						var c = _toCamelCase(p);
						r[c] = this.camel(s[p]);
					}
					return r;
				} else {
					return s;
				}
			},
			isArray:function(o){
				return Object.prototype.toString.call(o) === '[object Array]';   
			},
			formatInterval:function(interval){
				if (!interval){
					return "";
				}
				var hour = Math.floor(interval / 60);
				var minite = interval % 60;
				var r = "";
				if (hour != 0){
					r = hour+"小时";
				}
				if (minite != 0){
					r += minite +"分钟"; 
				}
				return r;
			},
			generateId:function(){
				var a = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';  
			    var str = '';   
			    var min = 0;    //包括   
			    var max = 61;//包括  
			    var len = 10;
			    for (var i = 0; i < len; i++)  
			    {   
			        var ran = Math.round(min + (Math.random() * (max - min)));   
			        str += a.charAt(ran);  
			    }   
			    return str;   
			},
			submitTripStep:function(post){
				var callback = post.callback || function(r){
					if (r.resultCode === '00000000' || r.resultCode === '10000000') {
						//成功跳转到添加想去的地方
						w.location.href = r.nextURL;
					} else{
						alert(r.resultMsg);
					}
				};
				$.post(post.path, {"data":$.toJSON(post.data),next:post.next},callback,'json');
			},
			createDeleteIcon:function(click){
				var $del = $("<a href='javascript:void(0)'>").click(click)
	    		.append("<img src='"+TripAPI.cpath+"/resources/portal/img/trip/del.png'/>");
				return $del;
			},
			Traffic:{
				types :[{from:0,to:0.5,speed:0.05,icon:"/resources/portal/img/trip/walk.png"},
				        {from:0.5,to:500,speed:1,icon:"/resources/portal/img/trip/car.png"},
				        {from:500,to:9999999999,speed:12,icon:"/resources/portal/img/trip/plane.png"}],
				selectType:function(d){
					var types = this.types;
					for (var i in types){
						var t = types[i];
						if (d >= t.from && d < t.to){
							return t;
						}
					}
				},
				calcTraffic:function(start,end){
					var d = Distance.calcDistance(start.lat,start.lng,end.lat,end.lng);
					if (isNaN(d)){
						d = 0;
					}
					var t = this.selectType(d);
					var time = Math.ceil(d / t.speed);
					return {
						distance:Distance.round(d,1),
						icon:TripAPI.cpath+t.icon,
						time:time,
						type:t
					};
				}
			}
	};
	w.TripAPI = TripAPI;
})($,window);

;(function ($,w){
	var TripAPI = w.TripAPI;
	/**
	 * 添加目的地
	*/
	var Tripdest = function(options){
		this.add_dests = [];
		this.orig_added_dests = [];
		this.opt = {};
		$.extend(this.opt,Tripdest.setting,options);
		//初始化,已经添加过的目的地
		var _this = this;
		var _opt = _this.opt;
		//初始化已经添加过的目的地的删除事件
		$(_opt.del_dest_btn).each(function(i,ele){
			var destData = $(ele).data();
			//$(ele).data("tripdest",destData);//绑定数据
			var $destView = _opt.crawlDestView(ele);
			var id  = TripAPI.generateId();
			destData._id = id;
			$destView.attr("id",id);
			//记录原始
			_this.orig_added_dests.push(destData);
			_this.add_dests.push(destData);
			$(ele).click(function(){
				//移除界面对象
				_opt.deleteHandle.call(_this,destData);
			});
		});
		
		//初始化目的地的添加事件
		$(_opt.add_dest_btn).each(function(i,ele){
			$(ele).click(function(){
				var d = $(this).data();
				_this.drawAddDest(d);
			});
		});
	};
	
	Tripdest.prototype.drawAddDest = function(d){
		if (_addDest.call(this,d)){
			d._id = TripAPI.generateId();
			var opt = this.opt;
			var $destView = opt.createDestView.call(this,d);
			$(opt.sel_dest_list).append($destView);
			this.edited = true;
		} else {
			alert("不要重复添加目的地");
		}
	};
	var _addDest = function(d){
		//1.需要验证是否已经添加过
		var addList = this.add_dests;
		if (d.tripdest_id == undefined){
			//如果行程目的地ID是undefined，说明是自定义的，自定义目的地直接添加
			for (var i in addList){
				if (addList[i].google_id == d.google_id){
					return false;
				}
			}
		} else {
			//验证系统目的地
			for (var i in addList){
				if (addList[i].tripdest_id == d.tripdest_id){
					return false;
				}
			}
		}
		addList.push(d);
		return true;
	};
	Tripdest.prototype.delDest = function(dest){
		var addList = this.add_dests;
		for (var i in addList){
			if (addList[i]._id == dest._id){
				//删除该元素
				addList.splice(i,1);
				break;
			}
		}
		this.edited = true;
	};
	Tripdest.prototype.hasDest = function(){
		return this.add_dests.length > 0;
	};
	Tripdest.prototype.edited = false;
	Tripdest.prototype.isEdited = function(){
		//是否添加，或者删除过数据
		return this.edited;
	};
	Tripdest.prototype.submit = function(tripId){
		//next：==true,表示下一步
		var curDests = this.add_dests;
		var origDests = this.orig_added_dests;
		//2.过滤出新添加的目的地
		//如果当前视图上已经添加的目的地，不在原始添加过的目的地中，则表示该目的地是新添加
		var addDests = $.grep(curDests,function (e){
			for (var j in origDests){
				if (e.tripdest_id == origDests[j].tripdest_id){
					return false;
				}
			}
			return true;
		});
		//2.过滤出删除已经添加过的目的地
		//如果原始添加的目的地，不在当前已经添加的目的地列表中，则表示该目的地删除了
		var deleteDests = $.grep(origDests,function (e){
			for (var j in curDests){
				if (curDests[j].tripdest_id == undefined || curDests[j].tripdest_id==e.tripdest_id){
					return false;
				}
			}
			return true;
		});
		var data = {"addDests":TripAPI.camel(addDests),"deleteDests":TripAPI.camel(deleteDests)};
		if (tripId){
			data.tripId = tripId;
		}
		var path = TripAPI.cpath+"/trip/edit/add-destination";
		TripAPI.submitTripStep({path:path,data:data,next:true});
	};
	Tripdest.setting = {
		sel_dest_list : "#selected_container",
		del_dest_btn : "#selected_container a",
		add_dest_btn : ".trip-area-mod-button a",
		deleteHandle : function(dest){
			$("#"+dest._id).remove();
			this.delDest(dest);
		},
		crawlDestView:function(dbtn){
			return $(dbtn).closest("li");
		},
		createDestView:function(d){
			var $d = $("<li>").attr("id",d._id).text(d.dest_name);
			var _this = this;
			var $del = TripAPI.createDeleteIcon(function(){
    			_this.opt.deleteHandle.call(_this,d);
    		});
//    		var $del = $("<a>").click(function(){
//    			_this.opt.deleteHandle.call(_this,d);
//    		})
//    		.attr("href","javascript:void(0)")
//    		.append("<img src='"+TripAPI.cpath+"/resources/portal/img/trip/del.png'/>");
    		//$del.data("tripdest",d);//绑定数据
    		$d.append($del);
    		return $d;
		}
	};
	$.fn.tripdest = function(opt){
		var element = $(this);
        // Return early if this element already has a plugin instance
        if (element.data('tripdest_plugin')) { return element.data('tripdest_plugin'); }
        // Pass options to plugin constructor
        var tripdestObj = new Tripdest(opt);
        // Store plugin object in this element's data
        element.data('tripdest_plugin', tripdestObj);
        return tripdestObj;
	};
})(jQuery,window);

;(function($,window){
	
	var _init = function(opt){
		var rowSize = this.getRowSize();
		if (rowSize == 0){
			//需要添加一个空行
			//添加行
			var $r = this.insertRowView();
			//添加控内容
			this.getRowHeaderView($r).after(_create_itemnull());
		} else {
			//选中第一行
			//选择第一行
			var $r = this.getRowView(0);
			var _this = this;
			this.getRowContentView().each(function(index,element){
				$(this).click(function(){
					_this.selectRowView($(this).closest(_this.opt.srow));
				});
			});
			this.selectRowView($r);
		}
		
		//初始化目的地的事件
		var _this = this;
		$(".trip-area-menu2 a").click(function(){
			_this.loadCategory($(this));
		});
		//默认加载第一个目的地的类别
		$(".trip-area-menu2 a").first().click();
	};
	
	var _create_rowview = function (){
		return $("<div class='trip-area-have2-row'>").append(_create_rowinnerview());
	};
	var _create_rowinnerview = function(){
		return $("<div class='trip-area-have2-rowinner'>").append(_create_rowheadview()).append(_create_rowbodyview());
	};
	
	var _create_rowheadview = function(){
		return $("<div class='item1 item1 trip-area-have-days-title'>");
	};
	
	var _create_rowbodyview = function(){
		return $("<div class='trip-area-have-days-info'>").append($("<ul>"));
	};
	var _create_itemnull = function (){
		return $("<div class='itemnull'>添加想去的地方</div>");
	};
	
	var Tripdaily = function(options){
		this.opt = {};
		$.extend(true,this.opt,Tripdaily.setting,options);
		_init.call(this,this.opt);
	};
	
	Tripdaily.setting = {
			stable:".trip-area-have2",
			srow:".trip-area-have2-row",
			srowheader:".trip-area-have-days-title",
			srowcontent:".trip-area-have2-rowinner",
			srowbody:".trip-area-have-days-info",
			scolumn:"li",
			sdest:".trip-area-menu2 li",
			changeDest:$.noop
	};
	
	Tripdaily.prototype.loadCategory = function($dest){
		$(".trip-area-menu2-submenu").each(function(){
			$(this).hide();
		});
		//清除选中的样式
		$(".trip-area-menu2 a").removeClass("cur");
		$dest.addClass("cur");
		var $category = $dest.next();
		var data = $dest.data();
		//验证该目的地的类别是否加载过
		var _this = this;
		if (!$category.data("loaded")){
			$category.data("loaded",true);
			$.get(TripAPI.cpath+"/trip/edit/add-location/category?tdid="+data.tripdest_id, function(data,status){
				 $category.html(data);
				 $category.show();
				 var defaultLoadCategory;
				 $category.find("a").each(function(i,e){
					 if (i == 0){
						 defaultLoadCategory = e;
					 }
					 $(e).click(function(){
						 _this.loadLocations($(e));
					 });
				 });
				 $(defaultLoadCategory).click();
			});
		} else{
			$category.show();
			$category.find("a").first().click();
		}
		this.selectedDest = data;
		//xiongxu 目的地切换，需要设置地图的center
		this.opt.changeDest.call(this,data);
	};
	
	Tripdaily.prototype.loadLocations = function($category){
		var data = $category.data();
		var _this = this;
		//清除选中的样式
		$("a",$category.closest("ul")).removeClass("cur");
		$category.addClass("cur");
		$.get(TripAPI.cpath+"/trip/edit/add-location/locations?tdid="+data.tripdest_id+"&cid="+data.category_id, function(data,status){
			var $con = $(".trip-area-list");
			$con.html(data);
			$con.find("a").each(function(i,e){
				$(e).click(function(){
					var data = $(e).closest(".trip-area-mod").data();
					 _this.insertColumn(data);
				});
			 });
		});
	};
	Tripdaily.prototype.getRowSize = function(){
		return this.getRowView().length;
	};
	
	Tripdaily.prototype.getTableView = function(){
		return $(this.opt.stable);
	};
	
	Tripdaily.prototype.getRowView = function(i){
		var rows = this.getTableView().find(this.opt.srow);
		if (i == undefined){
			return rows;
		}else {
			return rows.eq(i);
		}
	};
	
	Tripdaily.prototype.getRowHeaderView = function($r){
		if ($r == undefined){
			return this.getTableView().find(this.opt.srowheader);
		}
		return $r.find(this.opt.srowheader);
	};
	Tripdaily.prototype.getRowBodyView = function($r){
		return $r.find(this.opt.srowbody);
	};
	Tripdaily.prototype.getRowContentView = function($r){
		if ($r){
			return $r.find(this.opt.srowcontent);
		}
		return this.getTableView().find(this.opt.srowcontent);
	};
	Tripdaily.prototype.getRowColumnsView = function($r){
		return this.getRowBodyView($r).find(this.opt.scolumn);
	};
	Tripdaily.prototype.selectRowView = function($r){
		var $rc = $r.find(this.opt.srowcontent);
		//设置选中样式
		$rc.addClass("selected");
		
		//行选中后，删除点击事件
		$rc.unbind("click");
		
		//添加location的删除图标
		var _this = this;
		this.attachHandler($r);
		
		//隐藏上次选中的行
		var $pr = this.selectedRow;
		this.unselectRowView($pr);
		this.selectedRow = $r;
		//重新设置列头
		this.refreshRowHeader();
		
		//添加增加下一行的添加图标
		var $i = $("<img>").attr("src",TripAPI.cpath+"/resources/portal/img/trip/add2.png");
     	var $a = $("<a href='javascript:void(0)'>").click(function (){
     		//添加新的一行
     		_this.insertRowView($r);
     		}).append($i);
     	var $add = $("<div class='trip-area-have2-rowadd'>").append($a);
     	$r.append($add);
	};
	
	Tripdaily.prototype.attachHandler = function($r){
		var _this = this;
		this.getRowColumnsView($r).each(function(i,e){
			//生成删除事件，和绑定周边查看的事件
			$(e).append(TripAPI.createDeleteIcon(function (){
				_this.deleteColumnView($(e));
			}));
		});
	};
	Tripdaily.prototype.unselectRowView = function($r){
		if (!$r){
			return;
		}
		var $rc = this.getRowContentView($r);
		$rc.removeClass("selected");
		
		//增加行点击事件,选中该行
		var _this = this;
		$rc.click(function(){
			_this.selectRowView($r);
		});
		//删除location的删除图标
		$r.find("ul a").remove();
		//如果该行是空行，可能有空内容，需要删除
		$r.find(".itemnull").remove();
		//删除添加行的图标
		$('.trip-area-have2-rowadd').remove();
		this.selectedRow = null;
	};
	
	Tripdaily.prototype.refreshRowHeader = function(){
		var $s = this.selectedRow;
		var sindex = - 1;
		if ($s){
			sindex = $s.index();
		}
		var _this = this;
		this.getRowHeaderView().each(function(i,e){
			if (i != sindex){
				$(this).text("第" + (i + 1) + "天");
			} else {
				var $di = $("<img>").attr("src",TripAPI.cpath+"/resources/portal/img/trip/close.png");
				var $r = $(this).closest(_this.opt.srow);
				var $d = $("<div class='itemCloase'>").append($di).click(function(){
					_this.deleteRowView($r);
				});
				$(this).text("").append($d);
			}
		});
	};
	Tripdaily.prototype.insertRowView = function($preRow){
		var $r = _create_rowview();
		if ($preRow == undefined){
			this.getTableView().append($r);
		} else {
			$preRow.after($r);
		}
		//设置选中
		this.selectRowView($r);
		this.updateAdd = true;
		return $r;
	};
	Tripdaily.prototype.insertColumn = function(data){
		$r = this.selectedRow;
		if (!$r){
			alert("请选择将该地方添加到哪天");
			return;
		}
		$r.find(".itemnull").remove();
		var $cells = $r.find("ul");
		var $cell = $("<li>").text(data.location_name);
		$cell.data(data);
		var _this = this;
		$cell.append(TripAPI.createDeleteIcon(function(){
			_this.deleteColumnView($cell);
		}));
		$cells.append($cell);
		this.updateAdd = true;
		return $cell;
	};
	
	Tripdaily.prototype.deleteRowView = function($r){
		var nextSelectedRow = $r.next();
		if (!nextSelectedRow){
			nextSelectedRow = $r.prev();
		}
		if (!nextSelectedRow){
			alert("必须要有一天行程");
			return;
		}
		var data = $r.data();
		if (data.daily_id){
			this.deleteRows.push(data);
			var _this = this;
			this.getRowColumnsView($r).each(function(i,e){
				_this.deleteColumnView($(e));
			});
		}
		$r.remove();
		this.selectedRow = null;
		this.selectRowView(nextSelectedRow);
	};
	
	Tripdaily.prototype.deleteColumnView = function($c){
		var data = $c.data();
		if (data.daily_location_id){
			this.deleteColumns.push(data);
		}
		$c.remove();
	};
	
	Tripdaily.prototype.isEdited = function(){
		return (this.deleteRows.length > 0 || this.deleteColumns.length > 0 || this.updateAdd);
	};
	
	Tripdaily.prototype.submit = function(next,tripId){
		var dailys = [];
		if (this.updateAdd){
			var _this = this;
			this.getRowView().each(function(i,r){
				var d = $(r).data();
				d.tripDailyLocations = [];
				dailys.push(d);
				$(r).find("li").each(function(i,c){
					var cdata = $(c).data();
					d.tripDailyLocations.push(cdata);
				});
			});
		}
		var path = TripAPI.cpath+"/trip/edit/add-location";
		var data = {deleteDailys:this.deleteRows,deleteLocations:this.deleteColumns,updateDailys:dailys,"tripId":tripId};
		TripAPI.submitTripStep({path:path,data:TripAPI.camel(data),next:next});
	};
	
	Tripdaily.prototype.updateAdd = false;
	Tripdaily.prototype.deleteRows = [];
	Tripdaily.prototype.deleteColumns = [];
	Tripdaily.prototype.selectedRow = null;
	Tripdaily.prototype.selectedDest = null;
	$.fn.tripdaily = function(opt){
		var $this = $(this);
		if ($this.data("tripdaily_plugin")){return $e.data('tripdaily_plugin'); }
		var obj = new Tripdaily(opt);
		$this.data('tripdaily_plugin', obj);
        return obj;
	};
	
})(jQuery,window);

;(function($,w){
	var TripToggle = function($button,options){
		//默认没有展开
		this.opt = {};
		$.extend(this.opt,TripToggle.setting,options);
		var _this = this;
		this.$button = $button;
		$button.click(function(){
			_this.click();
		});
	};
	TripToggle.prototype.click = function(){
		//如果当前是展开，则触发collapse
		if (this.opt.expandable){
			this.collapse();
		} else {
			this.expand();
		}
	};
	TripToggle.prototype.expand = function(){
		var $btn = this.$button;
		this.opt.expandable = true;
		if (this.opt.iconable){
			$btn.css("background-image","url("+TripAPI.cpath + this.opt.collapseIcon+")"); 
		}
		this.opt.one.call($btn[0]);
	};
	TripToggle.prototype.collapse = function(){
		var $btn = this.$button;
		this.opt.expandable = false;
		if (this.opt.iconable){
			$btn.css("background-image","url("+ TripAPI.cpath +this.opt.expandIcon+")"); 
		}
		this.opt.two.call($btn[0]);
	};
	TripToggle.setting = {
			expandable:false,
			one:$.noop,
			two:$.noop,
			expandIcon:"/resources/portal/img/trip/mapcontrol.png",
			collapseIcon:"/resources/portal/img/trip/mapcollapse.png",
			iconable:true
	};
	
	$.fn.triptoggle = function(opt){
		$(this).each(function(i,ele){
			  // Return early if this element already has a plugin instance
			var $e = $(ele);
	        if ($e.data('triptoggle_plugin')) { return $e.data('triptoggle_plugin'); }
	        // Pass options to plugin constructor
	        var toggleObj = new TripToggle($e,opt);
	        // Store plugin object in this element's data
	        $e.data('triptoggle_plugin', toggleObj);
		});
	};
})(jQuery,window);

;(function($,window){
	var _initMap = function(){
		var _opt = this.opt;
		var mapOptions = {
   				zoom:_opt.zoom,
   				center: _opt.center,
   				//disableDefaultUI: true,
   				scrollwheel:false,
   				mapTypeId: google.maps.MapTypeId.ROADMAP
   		};
		this.map = new google.maps.Map(this.mapDom,mapOptions); 
		this.markers = [];
		this.markerLines = [];
		this.infoWindow =  new google.maps.InfoWindow(_opt.infoWindow);
		
		//支持place查询
		var search = _opt.search;
		if (search.input){
			_initMapSearch.call(this,search);
		}
		//支持地图区域绘制
		if (_opt.drawenable){
			_initDrawer.call(this);
		}
	};
	
	var _initMapSearch = function(search){
		this.searchService = new google.maps.places.PlacesService(this.map);
		//var options = {bounds: defaultBounds,types: ['establishment']};
		//绑定查询提交按钮事件
		$(search.submit).click($.proxy(_onSubmit,this));
		//绑定选中区域
		var _this = this;
		$(search.bound).triptoggle({
			one:function(){
				_this.startDraw();
				$(this).val("停止选择");
			},
			two:function(){
				_this.stopDraw();
				$(this).val("选择区域");
			},
			iconable:false
		});
		$(search.clearBound).click(function(){
			_this.clearDrawBound();
		});
		//绑定自动补全
		this.autocomplete = new google.maps.places.Autocomplete($(search.input)[0], {});
		google.maps.event.addListener(this.autocomplete, 'place_changed',$.proxy(_onAutocompleteChanged,this));
	};
	
	var _onSubmit = function(){
		var _opt = this.opt;
		var value = $(_opt.search.input).val();
		if (!value){
			alert("请输入你要查询的名称");
		}
		
		_opt.search.before.call(this);
		var request = {query: value};
		//查询开始,这里需要验证是否有bounds限制，否则需要bounds查询
		if (this.drawBound){
			request.bounds = this.drawBound.getBounds();
		}
		this.searchService.textSearch(request, $.proxy(_onSearchCallback,this));
	};
	
	var _onSearchCallback = function(results,status){
		if (status == google.maps.places.PlacesServiceStatus.OK) {
			//清除原来的marker
			this.clearMarkers();
		    for (var i = 0; i < results.length; i++) {
		    	this.createMarker('place',results[i]);
		    }
			if(results.length > 0){
				_fitBoundsByPlace.call(this,results[0]);
			}
		} else {
			this.opt.onSearchError.call(this,status);
		}
	};
	
	var _onAutocompleteChanged = function(){
		this.clearMarkers();
		var place = this.autocomplete.getPlace();
		_fitBoundsByPlace.call(this,place);
		this.createMarker('place',place);
	};
	
	var _fitBoundsByPlace = function(place){
		var _map = this.map,_opt = this.opt;
		if (place.geometry.viewport) {
			_map.fitBounds(place.geometry.viewport);
		} else {
			_map.setCenter(place.geometry.location);
			_map.setZoom(_opt.zoom);
		}
	};

	var _initDrawer = function(){
		this.drawer = new google.maps.drawing.DrawingManager({drawingControl: false});
		this.drawer.setMap(this.map);
		google.maps.event.addListener(this.drawer,'rectanglecomplete',$.proxy(_onDrawComplete,this));
	};

	var _onDrawComplete = function(rect){
		this.clearDrawBound();
		this.drawBound = rect;
		//还需要设置complete的
		if (this.autocomplete){
			this.autocomplete.setBounds(rect.getBounds());
		}
	};
	
	var Map = function(mapDom,options){
		this.opt = {};
		this.mapDom = mapDom;
		$.extend(true,this.opt,Map.setting,options);
		//如果地图不是延迟加载
		if (!this.opt.lazy && this.isShowing()){
			_initMap.call(this);
		}
	};
	Map.prototype.isShowing = function(){
		return !$(this.mapDom).is(":hidden");
	};
	
	Map.prototype.show = function(){
		//地图是否初始化
		if (!this.map){
			_initMap.call(this);
		}
		$(this.mapDom).show();
	};
	Map.prototype.createMarker = function(type,data){
		var m;
		if (type= 'place'){
			m = this.opt.createPlaceMarker.call(this,data);
		}
		this.markers.push(m);
	};
	Map.prototype.createMarkers = function(items){
		this.clearMarkers();
		var markers = this.markers;
		var map = this.map;
		$.each(items,function(i,e){
			var latLng =  new google.maps.LatLng(e.lat, e.lng);
			var marker = new google.maps.Marker({
				position : latLng,
				map : map,
				title:e.location_name,
				icon:{
		     	 	origin: new google.maps.Point(0, 0),
		     		anchor:new google.maps.Point(14,38),
		     		size : new google.maps.Size(28,38),
		     		url:TripAPI.cpath+"/resources/portal/img/googlemap/"+(i+1)+".png"
		     	}
			});
			markers.push(marker);
		});
	};
	
	Map.prototype.adjustMapView = function(){
		if (this.markers.length == 1){
			var m = this.markers[0];
			this.map.setCenter(m.getPosition());
			this.map.setZoom(this.opt.zoom);
		} else if (this.markers.length > 1){
			var bounds = new google.maps.LatLngBounds();
		 	$.each(this.markers,function(i,m){
		 		bounds.extend(m.getPosition());
		 	});
		 	this.map.setCenter(bounds.getCenter());
	     	this.map.fitBounds(bounds);
		}
		
	};
	Map.prototype.clearMarkers = function(){
		var markers = this.markers;
		for (var i in markers){
			markers[i].setMap(null);
		}
		var lines = this.markerLines;
		for (var i in lines){
			lines[i].setMap(null);
		}
		markers.length = 0;
		lines.length = 0;
	};
	
	Map.prototype.linkMarkers = function(){
		//连接markers
		var lineSymbol = {path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW};
//		// 添加线
		var map = this.map;
		var markers = this.markers;
		var lines = this.markerLines;
		$.each(markers,function(i,t){
			if (i > 0){
				var f = markers[i -1];
				var line = new google.maps.Polyline({
				  path : [f.getPosition(),t.getPosition()],
				  strokeColor : '#ff8700',
				  strokeOpacity : 1.0,
				  strokeWeight : 2,
				  //icons: [{icon: lineSymbol,offset: '100%'}],
				  map: map
				});
				lines.push(line);
			}
		});
	};
	Map.prototype.hide = function(){
		$(this.mapDom).hide();
	};
	Map.prototype.clearDrawBound = function(){
		if (this.drawBound){
			this.drawBound.setMap(null);
			//清除自动补全的bounds
			if (this.autocomplete){
				this.autocomplete.setBounds(null);
			}
		}
	};
	Map.prototype.startDraw = function(){
		var drawer = this.drawer;
		if (drawer){
			drawer.setOptions({drawingMode: google.maps.drawing.OverlayType.RECTANGLE});
		}
	};
	Map.prototype.stopDraw = function(){
		var drawer = this.drawer;
		if (drawer){
			drawer.setOptions({drawingMode: null});
		}
	};
	Map.prototype.openWindow = function(content,marker){
		var _win = this.infoWindow;
		  _win.setContent(content);
		  _win.open(this.map, marker);
	};
	Map.prototype.closeWindow = function(){
		this.infoWindow.close();
	};
	Map.prototype.setCenter = function(center){
		var latlng = new google.maps.LatLng(center.lat, center.lng);
		if (this.isShowing()){
			this.map.setCenter(latlng);
		}else {
			this.opt.center = latlng;
		}
	};
	
	Map.prototype.isInited = function(){
		return this.map ? true : false;
	};
	Map.setting = {
			lazy:true,
			center: new google.maps.LatLng(39.90403, 116.40752599999996),//默认北京
			zoom:12,
			search:{
				input:null,
				submit:null,
				before:$.noop,
				after:$.noop,
				bound:null,
				clearBound:null
			},
			infoWindow:{
				maxWidth:270
			},
			drawenable:false,
			createPlaceMarker:function(place){
				  var pos = place.geometry.location;
				  var _map = this.map,_win = this.infoWindow;
				  var marker = new google.maps.Marker({map: _map,position: pos,title:place.name});
				  var _this = this;
				  google.maps.event.addListener(marker, 'click',function(){
					  var content = _this.opt.renderMarkerWindowContent.call(_this,place);
					  _this.openWindow(content,this);
					  $(".trip-area-map-windowshow-button a").click(function(){
						  _this.opt.addPlace.call(_this,place);
					  });
				  });
				  return marker;
			},
			renderMarkerWindowContent:function(markerData){
				var $win = $("<div class='trip-area-map-windowshow'>");
				var $title = $("<div class='trip-area-map-windowshow-title'>").text(markerData.name);
				
				var content = "纬度:"+markerData.geometry.location.lat()+"<br>";
				content +="经度:"+markerData.geometry.location.lng()+"<br>";
				content +="地址:"+markerData.formatted_address;
				var $info = $("<div class='trip-area-map-windowshow-info'>").html(content);
				var _this = this;
				var $addBtn = $("<a class='add' href='javascript:void(0)'>").text("添加");
				var $add = $("<div class='trip-area-map-windowshow-button'>").append($addBtn);
				$win.append($title).append($info).append($add).append("<div class='clear'></div");
				return $win.html();
			},
			onSearchError:function(status){
				var PSS = google.maps.places.PlacesServiceStatus;
				if (status == PSS.ERROR){
					alert("连接 Google 服务器时出现问题");
				}else if (status == PSS.INVALID_REQUEST){
					alert("请求无效");
				}else if (status == PSS.OVER_QUERY_LIMIT){
					alert("网页已超出其请求配额");
				}else if (status == PSS.REQUEST_DENIED){
					alert("网页已禁止使用地方信息服务");
				}else if (status == PSS.UNKNOWN_ERROR){
					alert("地方信息服务因服务器出错而无法得到处理,如果您重试一次，该请求可能就会成功.");
				}else{
					alert("找不到关于此请求的任何结果");
				}
			},
			addPlace:$.noop
	};
	
	$.fn.tripmap = function(opt){
		var $this = $(this);
		if ($this.data("tripmap_plugin")){return $this.data('tripmap_plugin'); }
		var map = new Map($this[0],opt);
		$this.data('tripmap_plugin', map);
        return map;
	};
})(jQuery,window);

;(function($){
	var Sort = function(opt){
		var s = this;
		this.opt = $.extend(true,{},Sort.setting,opt);
		
		var dragSetting = this.opt.dragger;
		var dragger = $(dragSetting.contSelector).tablesort(dragSetting);
		this.dragger = dragger;
		//绑定行的点击事件
		dragger.bindForRow("click",$.proxy(this.rowClicked2,this)).bindForRow("dropEnd",$.proxy(this.dropRow,this));
		dragger.bindForCells("dragStart",$.proxy(this.dragCell,this)).bindForCells("dropEnd",$.proxy(this.dropCell,this));
		//默认触发第一个
		this.rowClicked2(dragger,dragger.getRow(0));
	};
	
	Sort.prototype.dragCell = function (dragger,cell){
		//记录当前单元的所在的row
		var row = dragger.findRow(cell);
		//记录被拖拽的单元的原始所在的行
		cell.from = row;
		return true;
	};
	
	Sort.prototype.dropCell = function (dragger,cell){
		//如果当前被选中的行，是否有增加或移动元素，需要同步刷新地图
		var curRow = dragger.findRow(cell);
		var sRow = this.selectedRow;
		//刷新地图
		if (curRow == sRow || cell.from == sRow){
			this.drawMap(sRow);
		}
		this.edited = true;
	};
	
	Sort.prototype.dropRow = function (dragger,row){
		var dragSetting = this.opt.dragger;
		$(dragSetting.contSelector).find(dragSetting.rowHeadSelector).each(function(index,item){
			$(this).text("第"+(index+1)+"天");
		});
		//刷新天的编号
		if (this.selectedRow == row){
			_drawDayNo(row);
		}
		this.edited = true;
	};
	
	Sort.prototype.rowClicked2 = function(dragger,row){
		//1.移除上次选中的行
		var selectedRow = this.selectedRow;
		var _t = this;
		if (selectedRow){
			var moveItem = selectedRow.getMoveItem();
			//移除高亮
			moveItem.removeClass("selected");
			//禁用拖拽
			selectedRow.enableDrag(false);
			//重新绑定点击事件
			var dragItem = selectedRow.getDragItem();
			dragItem.bind("click", function() {
				($.proxy(_t.rowClicked2,_t))(dragger,selectedRow);
			});
		}
		//2.设置当前行未选中行,并且高亮选中框
		this.selectedRow = row;
		//添加高亮
		row.getMoveItem().addClass("selected");
		//设置移动
		row.enableDrag(true);
		//移除点击事件，避免重复刷新地图等。
		row.getDragItem().unbind("click");
		//3.刷新地图，刷新地图列表
		this.drawMap(row);
	};
	
	Sort.prototype.drawMap = function(row){
		if (!row){
			row = this.selectedRow;
		}
		//记录当前行的数据size
		var map = this.opt.map;
		if (map){
			var data = this.getRowData(row);
			//1.绘制地图
//			map.refresh(data);
			map.show();
			map.createMarkers(data.items);
			map.linkMarkers();
			map.adjustMapView();
			//2.绘制天的标题
			_drawDayNo(row);
			//设置标题
			var title = "<em>第"+data.dayNo+"天</em>"+data.dests.join(" ");
			$(".step3-info-title").html(title);
			$(".infoa").text(data.items.length+" 地点");
			$(".infob").text(data.distance+" 公里");
			$(".infoc").text(TripAPI.formatInterval(data.time));
			var $items = $(".step3-info-l");
			$items.html('');//清空原来的
//			 border-top: 1px solid #CCCCCC;
			var itemCount = data.items.length;
			$.each(data.items,function(i,e){
				var $i = _buildItem(i + 1,e);
				$items.append($i);
				if (i ==itemCount - 1){
					$i.css("border-bottom","1px solid #CCCCCC");
				}
			});
			$items.append("<div class='clear'>");
			//调用插件设置图片居中显示  xjr
			$(".step3-info-m-img").imgresize();
		}
	};
	var _buildItem = function(index,data){
		
		
		var $imgdiv = $("<div class='step3-info-m-img'>");
		
		if (data.image){
			var $img = $("<img>").attr("src",data.image);
			$imgdiv.append($img);
		}
		
		var traffic = data.traffic;
		var title= "<em>"+index+".</em>&nbsp;&nbsp;"+data.location_name;
		if (traffic){
			title+="<span class='otherlength'>距离:"+ traffic.distance +" 公里";
			title+="<img src='"+traffic.icon+"'/>" ;
			title+="<span class='othertime'>"+TripAPI.formatInterval(traffic.time)+"</span>";
		}
		if (data.stay_time){
			title += "<span class='otherline'>停留"+TripAPI.formatInterval(data.stayTime)+"</span>";
		}
		var $title = $("<div class='step3-info-m-title'>").append(title);
		
		var $summary = $("<div class='step3-info-m-note'>").text(data.summary);
		
		return $("<div class='step3-info-m'>").append($imgdiv).append($title).append($summary);
	};
	var _drawDayNo = function(row){
		//第几天
		var moveItem = row.getMoveItem();
		var day = moveItem.index() + 1;
		$(".trip-area-step3-info-title").text("第"+day+"天");
	};
	
	Sort.prototype.getRowData = function(row){
		var moveItem = row.getMoveItem();
		var dayNo = moveItem.index() + 1;
		var items = [];
		var totalTime = 0;
		var totalDistance = 0;
		var dests = [];
		moveItem.find(this.opt.dragger.itemSelector).each(function(index,e){
			var data = $(e).data();
			items.push(data);
			//收集目的地
			if ($.inArray(data.dest_name,dests)== -1){
				dests.push(data.dest_name);
			}
			//计算距离
			if (index > 0){
				var traffic = TripAPI.Traffic.calcTraffic(data,items[index - 1]);
				data.traffic = traffic;
				totalTime += traffic.time;
				totalDistance += traffic.distance;
			}
		});
		//总距离，总时间
		return {
			items:items,
			dayNo:dayNo,
			time:totalTime,
			dests:dests,
			distance:totalDistance
		};
	};

	Sort.prototype.submit = function(next,tripId){
		var _this = this;
		var ds = this.opt.dragger;
		var dragger = this.dragger;
		var updateDailys = [],updateLocations = [],dests = [],points = [];
		$(ds.contSelector).find(ds.rowHeadSelector).each(function (index){
			var row = dragger.getRowByDragItem($(this));
			var moveItem = row.getMoveItem();
			var dd = moveItem.data();
			updateDailys.push({
				dailyId:dd.daily_id,
				dailyNo:(index+1)
			});
			moveItem.find(ds.itemSelector).each(function(index){
				var ld = $(this).data();
				var destName = ld.dest_name;
				if ($.inArray(destName,dests)== -1){
					dests.push(destName);
				}
				updateLocations.push({
					dailyLocationId:ld.daily_location_id,
					locationNo:index+1,
					dailyId:dd.daily_id
				});
				points.push(new google.maps.LatLng(ld.lat, ld.lng));
			});
		});
		
		var tripName;
		if (dests.length == 1){
			tripName = dests[0]+updateDailys.length+"日游";
		}else {
			tripName = dests[0]+"-"+dests[dests.length -1]+updateDailys.length+"日游";
		}
		if (tripName.length > 32){
			tripName = tripName.substr(tripName.length - 32);
		}
		var distance = 0;
		$.each(points,function(index,t){
			if (index > 0){
				var d = Distance.distance(points[index - 1],t);
				if (isNaN(d)){
					d = 0;
				}
				distance += d;
			}
		});
		distance = Distance.round(distance,0);
		var data;
		if (this.edited){
			data = {tripId:tripId,distance:distance,days:updateDailys.length,tripName:tripName,updateDailys:updateDailys,updateLocations:updateLocations};
		}else{
			data = {tripId:tripId,distance:distance,days:updateDailys.length,tripName:tripName};
		}
		var path = TripAPI.cpath+"/trip/edit/sort";
		TripAPI.submitTripStep({path:path,data:data,next:next});
	};
	Sort.prototype.dragger = null;
	Sort.prototype.selectedRow = null;
	Sort.prototype.edited = false;
	Sort.setting = {
			map:null,
			dragger:{
				contSelector:".table",
				itemSelector: ".cell",
		        rowBodySelector: ".row_body",
		        rowHeadSelector: ".row_header",
		        itemPlaceHolder: "<li class='cell'></li>",
		        rowPlaceHolder: "<div class='row trip-area-have2-row'></div>"
			}
	};
	
	$.fn.tripsort = function(opt){
		var $this = $(this);
		if ($this.data("tripsort_plugin")){return $e.data('tripsort_plugin'); }
		var sort = new Sort(opt);
		$this.data('tripsort_plugin', sort);
        return sort;
	};
})(jQuery);
